package com.bibrApp.difu.base;

import java.util.List;

import androidx.annotation.NonNull;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BasePermissionActivity<T extends BasePresenter> extends BaseActivity<T> {
    private OnPermissionCallBack permissionListener = null;
    private static final int PERMISSION_REQ = 0x1110;

    /**
     * 申请权限
     *
     * @param permissions          请求权限
     * @param onPermissionListener 回调函数
     */
    public void reqPermission(String[] permissions, OnPermissionCallBack onPermissionListener) {
        this.permissionListener = onPermissionListener;
        //请求权限
        if (EasyPermissions.hasPermissions(this, permissions)) {
            permissionListener.onGranted();
        } else {
            EasyPermissions.requestPermissions(this, "需要开启权限才能使用此功能", PERMISSION_REQ, permissions);
        }
    }


    /**
     * 申请权限的回调用
     *
     * @param requestCode  请求码
     * @param permissions  申请的权限
     * @param grantResults 授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, new EasyPermissions.PermissionCallbacks() {
            @Override
            public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
                if (requestCode != PERMISSION_REQ) {
                    return;
                }
                permissionListener.onGranted();
            }

            @Override
            public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
                if (EasyPermissions.somePermissionPermanentlyDenied(BasePermissionActivity.this, perms)) {
                    new AppSettingsDialog.Builder(BasePermissionActivity.this)
                            .setTitle("设置权限")
                            .setRationale("需要开启权限才能使用此功能")
                            .setPositiveButton("设置")
                            .setNegativeButton("取消")
                            .build()
                            .show();
                }
            }

            @Override
            public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            }
        });
    }


    public interface OnPermissionCallBack {
        void onGranted();
    }
}
